package com.yidu.logisticssystem.controller;

import com.google.gson.Gson;
import com.yidu.logisticssystem.entity.*;
import com.yidu.logisticssystem.entity.vo.LogisticsModVo;
import com.yidu.logisticssystem.entity.vo.LogisticsPostVo;
import com.yidu.logisticssystem.entity.vo.TreeResult;
import com.yidu.logisticssystem.entity.vo.Treeindex;
import com.yidu.logisticssystem.service.LogisticsModuleService;
import com.yidu.logisticssystem.service.LogisticsModxpostService;
import com.yidu.logisticssystem.service.LogisticsPostService;
import com.yidu.logisticssystem.utils.Tools;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模块表(LogisticsModule)表控制层
 *
 * @author 王锦程
 * @since 2021-03-12 15:39:50
 */
@RestController
@RequestMapping("logisticsModule")
public class LogisticsModuleController {
    /**
     * 服务对象
     */
    @Resource
    private LogisticsModuleService logisticsModuleService;
    @Resource
    private LogisticsPostService logisticsPostService;
    @Resource
    private LogisticsModxpostService logisticsModxpostService;

    @Resource
    RedisTemplate redisTemplate ;

    /**
     * 通过主键查询单条数据
     *
     * @param modId 主键
     * @return 单条数据
     */
    @ApiOperation("通过主键查询单条数据")
    @GetMapping("selectOne")
    public LogisticsModule selectOne(Integer modId) {
        //调用logisticsModuleService.queryById查询模块信息
        return this.logisticsModuleService.queryById(modId);
    }
    /**
     * 通过主键删除数据
     *
     * @param modId 主键
     * @return 单条数据
     */
    @ApiOperation("通过主键删除单条数据")
    @GetMapping("delete")
    public Map<String, Object> delete(Integer modId) {
        Map<String, Object> map = new HashMap<>();
        //调用logisticsModxpostService.deleteBymodId方法先删除对应的角色模块
        logisticsModxpostService.deleteBymodId(modId);
        //再调用logisticsModuleService.deleteById方法删除模块
        logisticsModuleService.deleteById(modId);
        map.put("mes","删除成功");
        return map;
    }

    /**
     * 修改数据
     * @param module 模块
     * @return 单条数据
     */
    @ApiOperation("修改数据")
    @GetMapping("updateMod")
    public Map<String, Object> updateMod(LogisticsModule module) {
        Map<String, Object>map = new HashMap<>();
        //调用logisticsModuleService.update方法进行修改
        logisticsModuleService.update(module);
        map.put("mes","操作成功");
        return map;
    }

    /**
     * 查询所有数据
     *
     * @return 所有数据
     */
    @ApiOperation("查询所有数据")
    @GetMapping("TreeTableMod")
    public Map<String, Object> TreeTableMod() {
        Map<String, Object>map = new HashMap<>();
        //此处调用logisticsModuleService.queryAllByLimit()构建树结构
        List<LogisticsModule> list = logisticsModuleService.queryAllByLimit();
        map.put("code",0);
        map.put("msg","");
        map.put("data",list);
        return map;
    }

    /**
     * 修改或增加角色权限
     */
    @ApiOperation(value = "修改角色权限")
    @PostMapping("updatePost")
    public Map<String, Object> updatePost(LogisticsPostVo postVo) {
        Map<String, Object>map = new HashMap<>();
        //新建post角色容器
        LogisticsPost post=new LogisticsPost();
        //如果角色id为空，则新增
        if (postVo.getPostId()==null){
            post.setPostId(postVo.getPostId());
            post.setSectionId(postVo.getSectionId());//将部门id加入角色
            post.setPostName(postVo.getPostName());//将角色名称加入到角色中
            LogisticsPost post1 = logisticsPostService.insert(post);//调用logisticsPostService.insert增加角色
            String[] modIds = postVo.getModIds().split(",");//postVo.getModIds().split()使用“，”分割前端传入的模块id
            for (int i = 0; i < modIds.length; i++) {
                LogisticsModxpost lmp = new LogisticsModxpost();//创建模块x角色容器
                lmp.setPostId(post1.getPostId());//接收新增的角色id
                lmp.setModId(Integer.valueOf(modIds[i]));//将模块id加入容器
                logisticsModxpostService.insert(lmp);//logisticsModxpostService.insert增加权限
            }
            //增加对应的上级
            for (int i = 0; i < modIds.length; i++) {
                LogisticsModxpost lmp = new LogisticsModxpost();
                //logisticsModuleService.queryById()根据分割的模块id查询对应的信息
                LogisticsModule module = logisticsModuleService.queryById(Integer.valueOf(modIds[i]));
                //如果上级id不等于0，则增加
                if (module.getModDownid()!=0) {
                    lmp.setPostId(post1.getPostId());//将新增的角色ID加入容器
                    lmp.setModId(Integer.valueOf(module.getModDownid()));//将上级id加入lmp容器
                    //logisticsModxpostService.queryByIdint(lmp)调用此方法查询模块，角色关联信息，如果为空则调用增加方法
                    LogisticsModxpost logisticsModxpost = logisticsModxpostService.queryByIdint(lmp);
                    if (logisticsModxpost==null) {
                        logisticsModxpostService.insert(lmp);//增加权限
                    }
                }
            }
        }else {
            //如果角色名不为空则调用logisticsPostService.update修改方法
            if (postVo.getPostName()!=null){
                post.setPostId(postVo.getPostId());//将postid加入post容器
                post.setPostName(postVo.getPostName());//将postname加入post容器
                post.setSectionId(postVo.getSectionId());//将postsectionid加入post容器
                logisticsPostService.update(post);
            }
            //首先调用logisticsModxpostService.deleteByPostId(postVo.getPostId())删除角色id对应的所有权限
            logisticsModxpostService.deleteByPostId(postVo.getPostId());
            //分割传回来的角色id，重新赋予角色权限
            String[] modIds = postVo.getModIds().split(",");
            for (int i = 0; i < modIds.length; i++) {
                LogisticsModxpost lmp = new LogisticsModxpost();
                lmp.setPostId(postVo.getPostId());
                lmp.setModId(Integer.valueOf(modIds[i]));
                logisticsModxpostService.insert(lmp);
            }
            //增加对应的上级
            for (int i = 0; i < modIds.length; i++) {
                LogisticsModxpost lmp = new LogisticsModxpost();
                LogisticsModule module = logisticsModuleService.queryById(Integer.valueOf(modIds[i]));
                if (module.getModDownid()!=0) {
                    lmp.setPostId(postVo.getPostId());
                    lmp.setModId(Integer.valueOf(module.getModDownid()));
                    LogisticsModxpost logisticsModxpost=logisticsModxpostService.queryByIdint(lmp);
                    if (logisticsModxpost==null) {
                        logisticsModxpostService.insert(lmp);//增加权限
                    }
                }
            }
        }
        map.put("mes","操作成功");//将结果信息返回页面
        return map;
    }

    /**
     * 增加模块
     */
    @ApiOperation(value = "增加模块")
    @GetMapping("addMod")
    public Map<String, Object> addMod(LogisticsModule module) {
        System.out.println("上级权限id："+module.getModDownid()+"url地址："+module.getModUrl()+"模块名字："+module.getModName());
        Map<String, Object>map = new HashMap<>();
        if (module.getModDownid()==null){
            module.setModDownid(0);
        }
        //获取增加的模块id
        LogisticsModule insert = logisticsModuleService.insert(module);
        //getModDownid=0则说明是新建父节点，不需要加入到关联表中
        if (module.getModDownid()!=0){
            //根据上级id获得角色id
            List<LogisticsModxpost> mp = logisticsModxpostService.queryPostId(module.getModDownid());
            //将模块id和角色id加入到关联表中
            for (LogisticsModxpost lm:mp) {
                LogisticsModxpost lmp = new LogisticsModxpost();
                lmp.setPostId(lm.getPostId());
                lmp.setModId(insert.getModId());
                logisticsModxpostService.insert(lmp);
            }
        }
        map.put("mes","操作成功");
        return map;
    }


    /**
     * 查询所有数据
     */
    @ApiOperation(value = "遍历角色权限")
    @GetMapping("selectAll")
    public Map<String, Object> selectAll(Integer postId) {
        List<TreeResult> treeResults = (List<TreeResult>)redisTemplate.opsForValue().get("'"+postId+"'");
        if(treeResults==null){
            treeResults = new ArrayList<>();
            //查询所有根节点
            LogisticsModule module = new LogisticsModule();
            module.setModDownid(0);
            List<LogisticsModule> list = logisticsModuleService.queryAll(module);
            //根据id查询角色
            List<LogisticsModVo> listmod = logisticsPostService.queryBymodId(postId);
            //将对应的子节点加入到根节点下面
            for (LogisticsModule lm:list) {
                TreeResult treeResult = new TreeResult();
                //这里的循环是为了查询角色已经拥有的权限
                for (LogisticsModVo lmv:listmod) {
                    if (lmv.getModId()==lm.getModId()){
                        treeResult.setSelected(true);
                    }
                }
                treeResult.setName(lm.getModName());
                treeResult.setValue(String.valueOf(lm.getModId()));
                treeResult.setChildren(children(lm.getModId(),postId));
                treeResults.add(treeResult);
            }

            redisTemplate.opsForValue().set("'"+postId+"'",treeResults);
        }
        Map<String, Object> map = new HashMap();
        map.put("data",treeResults);
        return map;
    }

    /**
     * 遍历下级节点
     * @param childid
     * @return
     */
    public List<TreeResult> children(Integer childid,Integer postId){
        List<TreeResult> treeResults = new ArrayList<>();
        //根据id查询角色
        List<LogisticsModVo> listmod = logisticsPostService.queryBymodId(postId);
        List<LogisticsModule> list = logisticsModuleService.queryChildren(childid);//根据上级id遍历下级节点
        for (LogisticsModule mod:list) {
                TreeResult treeResult =  new TreeResult();
            for (LogisticsModVo lmv:listmod) {
                if (lmv.getModId()==mod.getModId()){
                    treeResult.setSelected(true);
                }
            }
                treeResult.setName(mod.getModName());
                treeResult.setValue(String.valueOf(mod.getModId()));
                treeResults.add(treeResult);
        }
        return treeResults;
    }


    /**
     * 取得登录的员工信息
     */
    @ApiOperation(value = "取得登录的员工信息")
    @GetMapping("islogin")
    public Map<String, Object> login(HttpSession session){
        Map<String, Object> map = new HashMap<>();
        List<Treeindex> treeindexs = new ArrayList<>();//树结构
        List<Treeindex> treeChildren = new ArrayList<>();//子节点
        //使用session.getAttribute取得登录的员工
        LogisticsStaff staff = (LogisticsStaff) session.getAttribute("staff");
        if (staff==null){//如果员工为空，说明登录的是用户,将用户信息返回到页面
            LogisticsUser user = (LogisticsUser)session.getAttribute("user");
            Treeindex treeindex = new Treeindex();
            treeindex.setModName("个人订单管理");
            treeindex.setModUrl("geren.html");
            treeChildren.add(treeindex);
            Treeindex treeindex1 = new Treeindex();
            treeindex1.setModName("运单管理");
            treeindex1.setModUrl("#");
            treeindex1.setChildren(treeChildren);
            treeindexs.add(treeindex1);
            map.put("post","user");
            map.put("data2",treeindexs);
            map.put("data",user);
        }else {
            //这里根据角色id查询模块
            List<LogisticsModVo> list = logisticsPostService.queryBymodId(staff.getPostId());
            //遍历list加入树结构
            for (LogisticsModVo modvo:list) {
                Treeindex treeindex = new Treeindex();
                treeindex.setModName(modvo.getModName());
                treeindex.setModUrl(modvo.getModUrl());
                List<Treeindex> listTrees = new ArrayList<>();
                for(LogisticsModVo modVoSub:list){
                    if(modvo.getModId()==modVoSub.getModDownid()){
                        Treeindex treeindex1 = new Treeindex();
                        treeindex1.setModName(modVoSub.getModName());
                        treeindex1.setModUrl(modVoSub.getModUrl());
                        listTrees.add(treeindex1);
                    }
                }
                treeindex.setChildren(listTrees); //设置子集
                if(!listTrees.isEmpty()) {
                    treeindexs.add(treeindex);
                }
            }
            map.put("post","staff");
            map.put("data2",treeindexs);
            map.put("data",staff);
        }
        return map;
    }

    @ApiOperation("清空session")
    @GetMapping("tologout")
    public String tologout(HttpServletRequest request){
        request.getSession().invalidate();//当点击退出按钮时，调用invalidate清空session
        return "login";
    }
}
